package com.yam.michael.hibernate.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.xunjia.exception.XunjiaException;
import com.yam.michael.hibernate.dao.AdvActivityDao;
import com.yam.michael.hibernate.pojo.AdvActivity;

public class AdvActivityDaoImpl extends HibernateDaoSupport implements AdvActivityDao,Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5425226659051939085L;
	//日志
	private static final Logger logger = Logger.getLogger(AdvActivityDaoImpl.class);
	@Override
	/**
	 * 添加广告群组信息
	 * @param advActivity
	 * @return
	 * @throws XunjiaException
	 */
	public Long addAdvActivity(AdvActivity advActivity)
			throws XunjiaException {
		try {
			return (Long) this.getHibernateTemplate().save(advActivity);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("添加广告活动发生错误,添加失败!!!!");
		}
	}

	@Override
	/**
	 * 删除广告活动信息
	 * @param advActivity
	 * @throws XunjiaException
	 */
	public void deleteActivity(AdvActivity advActivity) throws XunjiaException {
		try {
			this.getHibernateTemplate().delete(advActivity);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("删除广告活动发生错误,删除失败!!!!");
		}
	}

	@Override
	/**
	 * 更新广告活动信息
	 * @param advActivity
	 * @throws XunjiaException
	 */
	public void updateActivity(AdvActivity advActivity) throws XunjiaException {
		try {
			this.getHibernateTemplate().saveOrUpdate(advActivity);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("更新广告活动发生错误,更新失败!!!!");
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 按广告系列ID获取广告活动
	 * @return
	 * @throws XunjiaException
	 */
	public List<AdvActivity> getAdvActivity(final long sid) throws XunjiaException {
		return (List<AdvActivity>) this.getHibernateTemplate().execute(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery("FROM AdvActivity AS a WHERE a.sid=?");
				q.setLong(0, sid);
				return q.list();
			}});
	}

}
